#include "sync_redis.hpp"
#include "actor.h"
#include <atomic>
std::string rand_str(int len) {
	std::string str;
	int i = 0;
	for (i = 0; i < len; ++i) {
		str += 'A' + rand()%26;
	}
	str[++i] = '\0';
	return str;
}
int main(int argc , char *argv[] )
{
    const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
    int port = (argc > 2) ? atoi(argv[2]) : 6379;
    std::string  pass = (argc > 3) ? argv[3] : "";
    int count = (argc > 4) ? atoi(argv[4]): 10000; 
    int size = (argc > 5) ? atoi(argv[5]): 1; 
    int thrs = (argc > 6) ? atoi(argv[6] ): 4;
    int set = (argc > 7) ? atoi(argv[7]) : 0;
    if (strcmp(hostname,"-h") == 0)
    {
	printf("usage : hostname port pass  count size \n"); 
	return 0; 
    }

    if (pass == "false")
    {
	    pass = ""; 
    }


    SyncRedis syncRedis; 
    syncRedis.start(hostname ,port,pass, thrs); 


    //printf("cmd:%s size:%d count:%d threads:%d begin.\n\n", set?"hmset":"hmget", size*1024, count, thrs);
    auto start = std::chrono::system_clock::now();
    
    int processNum = 0;
    bool send = false;
    while (true) {
	syncRedis.process_result([&](RedisCommand *pRst){
	switch(pRst->type) {
	case EVT_RESULT:
	    processNum++;
	    //printf("++++++++++%d\n", processNum);
	    break;
	    }
	});

	if (processNum >= count) {
	    break;
	}
	if (send)
	{
	    continue;
	}
	send = true;
	char szBuf[32]= {0} ; 
	std::string str = rand_str(1024*size);
    	Actor actor;
    	actor.props = str+"props";
    	actor.props2 = str+"props2";
    	if (set) {
	    for(int i= 0;i < count; i++)
	    {
	    	sprintf(szBuf,"key%d",i);
	    	std::string user = szBuf; 
	    	syncRedis.execute(hmset(user, actor)); 
	    	//syncRedis.execute("HSET", "user1" , szBuf, szBuf); 
	    } 
        }
        else {
	    for (int i = 0; i < count; ++i) {
	        sprintf(szBuf, "key%d", i);
	    	std::string user = szBuf;
	    	syncRedis.execute(hmget(user));
	    } 
    	}
    }

    auto end = std::chrono::system_clock::now();
    auto escaped_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

    DLog("cmd:%s size:%d count:%d threads:%d escaped time:%lfsec", set?"hmset":"hmget", size*1024, count, thrs, double(escaped_time) / 1000);

    syncRedis.terminate();
    return 0; 
}
